
import * as crypto from 'crypto';

export class Auth {
    private secret:string = "xinigongsi_houtaimimao_jiamifuwen_zch4411416@qq.com";
    constructor(){}
    async createToken(userId:number|string,role:string){
        let obj2={
            userId,
            role,
            created:Date.now()/1000//token生成的时间的，单位秒
        };
        //payload信息
        var base64Str=Buffer.from(JSON.stringify(obj2),"utf8").toString("base64");

        var hash=crypto.createHmac('sha256',this.secret);
            hash.update(base64Str);
        var signature=hash.digest('base64');
        return  base64Str+"."+signature;
    }
    async decodeToken(token:string):Promise<boolean>{
        var decArr=token.split(".");
        if(decArr.length<2){
            //token不合法
            return true;
        }
        var payload={};
        //将payload json字符串 解析为对象
        try{
            payload=JSON.parse(Buffer.from(decArr[0],"base64").toString("utf8"));
        }catch(e){
            return true;
        }
        //检验签名
        try {
            var hash=crypto.createHmac('sha256',this.secret);
                hash.update(decArr[0]);
            var checkSignature=hash.digest('base64');
            if(checkSignature == decArr[1]){
                return true
            }else{
                return false
            }
        } catch (error) {
            return false
        }
    }

    async getUserInfo(token){
        var decArr=token.split(".");
        var payload={};
        //将payload json字符串 解析为对象
        try{
            payload=JSON.parse(Buffer.from(decArr[0],"base64").toString("utf8"));
            return payload
        }catch(e){
            return undefined;
        }
    }
}